﻿<!DOCTYPE html>
<head>
    <meta charset="UTF-8">

    <script type="text/javascript">

        var wsport = "5300"; 
		var wsserver = "ws://127.0.0.1:";
        var pc;
        var ws;

        async function start(url) {

            console.log(`start ${url}.`);
            alert(`подключаем веб сокет по адресу: ${url}`);
            closePeer();

            let videoControl = document.querySelector('#videoCtl');

            ws = new WebSocket(url, []);

            ws.onopen = async function () {
                console.log("web socket onopen.");

                pc = new RTCPeerConnection();

                pc.ontrack = ({ track, streams: [stream] }) => {
                    track.onunmute = () => {
                        console.log("Adding track to video control.");
                        videoControl.srcObject = stream;
                    };
                }; 				

            };

            ws.onmessage = async function (evt) {

                if (!evt.data.startsWith("v=")) {
                    console.log("Remote ICE candidate received.");
                    console.log(evt.data);
                    await pc.addIceCandidate({ candidate: evt.data, sdpMid: "0", sdpMLineIndex: 0 });
                }
                else {
                    // Received SDP offer from the remote web socket server.
                    console.log("Offer SDP received:");
                    console.log(evt.data);

                    await pc.setRemoteDescription(new RTCSessionDescription({ type: "offer", sdp: evt.data }))

                    // Now create our offer SDP to send back to the web socket server.
                    pc.createAnswer().then(function (answer) {
                        return pc.setLocalDescription(answer);
                    }).then(function () {
                        console.log("Sending answer SDP:");
                        console.log(pc.localDescription.sdp);
                        ws.send(pc.localDescription.sdp);
                    });
                }
            };
        };

        function closePeer() {
            console.log("close peer");
            if (ws != null) {
                ws.close();
            }

            if (pc != null) {
                pc.close();
            }
        };
		
		function wsupdate(){		
			wsport = document.getElementById("wsport").value;			
		};
		
		function getserver(){
			console.log(`wsport value ${document.getElementById("wsport").value}`)
			let url;
			if (document.getElementById("wsport").value == "")
			{
				url = wsserver + document.getElementById("wsport").placeholder + '/';
			}
			else{
				url = wsserver + document.getElementById("wsport").value + '/';
			}
						
			return url;
		};
		
		function fillWsPlaceholder(){
			console.log('fillPlaceholder');
			document.getElementsByName("wsport")[0].placeholder = wsport;
		
		};
		
		
		window.onload = (event) => {
			console.log('window.onload');
			fillWsPlaceholder();
		};

    </script>
</head>
<body>

    <video controls autoplay="autoplay" id="videoCtl" width="640" height="480"></video>
	<br>
	<label for="wsport">ws://localhost:</label><input type="text" id="wsport" name="wsport" ></input>

    <div>
        <!--<button type="button" class="btn btn-success" onclick="start(sendOfferUrl);">Start Send Offer</button>-->
        <button type="button" class="btn btn-success" onclick="start(getserver());">Start</button>
        <button type="button" class="btn btn-success" onclick="closePeer();">Close</button>
    </div>

</body>
